import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import pandas as pd

class TradeGUI:
    def __init__(self, root, trade_processor):
        self.root = root
        self.root.title("Trading Analyzer")
        self.trade_processor = trade_processor
        
        # 创建主框架
        self.main_frame = ttk.Frame(self.root, padding="10")
        self.main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 创建标签页
        self.notebook = ttk.Notebook(self.main_frame)
        self.notebook.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 创建各个标签页
        self.create_import_tab()
        self.create_trades_tab()
        self.create_stats_tab()
        
    def create_import_tab(self):
        """创建导入标签页"""
        import_frame = ttk.Frame(self.notebook, padding="10")
        self.notebook.add(import_frame, text="Import Orders")
        
        # 导入按钮
        ttk.Button(import_frame, text="Import Orders CSV", 
                  command=self.import_orders).grid(row=0, column=0, pady=5)
        
        # 添加状态标签
        self.status_label = ttk.Label(import_frame, text="")
        self.status_label.grid(row=1, column=0, pady=5)
        
    def create_trades_tab(self):
        """创建交易对标签页"""
        trades_frame = ttk.Frame(self.notebook, padding="10")
        self.notebook.add(trades_frame, text="Trades")
        
        # 创建交易对列表
        self.trades_tree = ttk.Treeview(trades_frame, columns=(
            'symbol', 'open_date', 'open_time',
            'close_date', 'close_time',
            'open_price', 'open_qty', 'close_price', 'close_qty',
            'direction', 'gross_profit', 'net_profit', 'commission',
            'holding_time', 'open_session', 'close_session', 'trade_type'
        ))
        
        # 设置列标题
        self.trades_tree.heading('symbol', text='Symbol')
        self.trades_tree.heading('open_date', text='Open Date')
        self.trades_tree.heading('open_time', text='Open Time')
        self.trades_tree.heading('close_date', text='Close Date')
        self.trades_tree.heading('close_time', text='Close Time')
        self.trades_tree.heading('open_price', text='Open Price')
        self.trades_tree.heading('open_qty', text='Open Qty')
        self.trades_tree.heading('close_price', text='Close Price')
        self.trades_tree.heading('close_qty', text='Close Qty')
        self.trades_tree.heading('direction', text='Direction')
        self.trades_tree.heading('gross_profit', text='Gross Profit')
        self.trades_tree.heading('net_profit', text='Net Profit')
        self.trades_tree.heading('commission', text='Commission')
        self.trades_tree.heading('holding_time', text='Holding Time')
        self.trades_tree.heading('open_session', text='Open Session')
        self.trades_tree.heading('close_session', text='Close Session')
        self.trades_tree.heading('trade_type', text='Trade Type')
        
        # 设置列宽
        for col in self.trades_tree['columns']:
            self.trades_tree.column(col, width=100)
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(trades_frame, orient=tk.VERTICAL, 
                                command=self.trades_tree.yview)
        self.trades_tree.configure(yscrollcommand=scrollbar.set)
        
        # 放置组件
        self.trades_tree.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        scrollbar.grid(row=0, column=1, sticky=(tk.N, tk.S))
        
        # 编辑按钮
        ttk.Button(trades_frame, text="Edit Selected Trade",
                  command=self.edit_trade).grid(row=1, column=0, pady=5)
        
    def create_stats_tab(self):
        """创建统计信息标签页"""
        stats_frame = ttk.Frame(self.notebook, padding="10")
        self.notebook.add(stats_frame, text="Statistics")
        
        # 统计信息显示区域
        self.stats_text = tk.Text(stats_frame, height=20, width=60)
        self.stats_text.grid(row=0, column=0, pady=5)
        
        # 刷新按钮
        ttk.Button(stats_frame, text="Refresh Statistics",
                  command=self.refresh_stats).grid(row=1, column=0, pady=5)
    
    def import_orders(self):
        """导入订单数据"""
        try:
            # 打开文件选择对话框
            file_path = filedialog.askopenfilename(
                title="Select Orders CSV File",
                filetypes=[("CSV files", "*.csv"), ("All files", "*.*")]
            )
            
            if not file_path:
                return
            
            # 读取CSV文件
            self.status_label.config(text="Reading CSV file...")
            self.root.update()
            
            # 尝试读取CSV文件
            try:
                # 尝试不同的编码方式
                encodings = ['utf-8', 'gbk', 'gb2312', 'utf-16']
                orders_df = None
                
                for encoding in encodings:
                    try:
                        orders_df = pd.read_csv(file_path, encoding=encoding)
                        break
                    except UnicodeDecodeError:
                        continue
                
                if orders_df is None:
                    raise ValueError("Could not read the file with any of the supported encodings")
                
                if orders_df.empty:
                    raise ValueError("CSV file is empty")
                
                # 检查必要的列是否存在
                required_columns = [
                    'Symbol', 'Side', 'Type', 'Qty', 'Filled Qty', 'Qty Left',
                    'Limit Price', 'Stop Price', 'Avg Fill Price', 'Status',
                    'Open Time', 'Close Time', 'Duration', 'Commission Fee',
                    'Expiration Date', 'Order ID'
                ]
                missing_columns = [col for col in required_columns if col not in orders_df.columns]
                
                if missing_columns:
                    raise ValueError(f"Missing required columns: {', '.join(missing_columns)}\n"
                                   f"Available columns: {', '.join(orders_df.columns)}")
                
                # 只保留已完成的订单
                orders_df = orders_df[orders_df['Status'] == 'Filled']
                
                # 确保数量为数字类型
                orders_df['Qty'] = pd.to_numeric(orders_df['Qty'], errors='coerce')
                orders_df['Filled Qty'] = pd.to_numeric(orders_df['Filled Qty'], errors='coerce')
                orders_df['Avg Fill Price'] = pd.to_numeric(orders_df['Avg Fill Price'], errors='coerce')
                orders_df['Commission Fee'] = pd.to_numeric(orders_df['Commission Fee'], errors='coerce')
                
            except pd.errors.EmptyDataError:
                raise ValueError("The CSV file is empty")
            except pd.errors.ParserError as e:
                raise ValueError(f"Error parsing CSV file: {str(e)}")
            
            # 处理订单数据
            self.status_label.config(text="Processing orders...")
            self.root.update()
            
            try:
                result = self.trade_processor.process_new_orders(orders_df)
                new_trades = result['new_trades']
                duplicate_orders = result['duplicate_orders']
                duplicate_trades = result['duplicate_trades']
                
                # 更新状态
                status_text = f"Import completed:\n"
                status_text += f"New trades: {len(new_trades)}\n"
                status_text += f"Duplicate orders: {len(duplicate_orders)}\n"
                status_text += f"Duplicate trades: {len(duplicate_trades)}"
                self.status_label.config(text=status_text)
                
                # 刷新交易对显示
                self.refresh_trades()
                
                # 显示成功消息
                messagebox.showinfo("Success", "Orders imported successfully!")
                
            except ValueError as ve:
                # 处理重复trade_id等业务逻辑错误
                error_msg = str(ve)
                messagebox.showerror("导入失败", error_msg)
                self.status_label.config(text="Import failed: Duplicate trade ID detected")
                return
            except Exception as e:
                # 处理其他未预期的错误
                error_msg = f"处理订单时发生未知错误: {str(e)}"
                messagebox.showerror("Error", error_msg)
                self.status_label.config(text="Import failed: Unknown error")
                return
            
        except Exception as e:
            error_msg = f"Failed to import orders: {str(e)}"
            messagebox.showerror("Error", error_msg)
            self.status_label.config(text="Import failed")
    
    def refresh_trades(self):
        """刷新交易对显示"""
        # 清空现有显示
        for item in self.trades_tree.get_children():
            self.trades_tree.delete(item)
            
        # 读取并显示交易对
        trades_df = self.trade_processor.file_handler.read_trades()
        for _, trade in trades_df.iterrows():
            self.trades_tree.insert('', 'end', values=(
                trade['symbol'],
                trade['open_date'],
                trade['open_time'],
                trade['close_date'],
                trade['close_time'],
                f"{trade['open_price']:.2f}",
                f"{trade['open_qty']:.0f}",
                f"{trade['close_price']:.2f}",
                f"{trade['close_qty']:.0f}",
                trade['direction'],
                f"{trade['gross_profit']:.2f}",
                f"{trade['net_profit']:.2f}",
                f"{trade['commission']:.2f}",
                trade['holding_time'],
                trade['open_session'],
                trade['close_session'],
                trade['trade_type']
            ))
    
    def edit_trade(self):
        """编辑选中的交易对"""
        selected = self.trades_tree.selection()
        if not selected:
            messagebox.showwarning("Warning", "Please select a trade to edit")
            return
        
        # 获取选中的交易对数据
        item = selected[0]
        values = self.trades_tree.item(item)['values']
        
        # 构建交易对数据字典
        trade_data = {
            'symbol': values[0],
            'open_date': values[1],
            'open_time': values[2],
            'close_date': values[3],
            'close_time': values[4],
            'open_price': float(values[5]),
            'open_qty': float(values[6]),
            'close_price': float(values[7]),
            'close_qty': float(values[8]),
            'direction': values[9],
            'gross_profit': float(values[10]),
            'net_profit': float(values[11]),
            'commission': float(values[12]),
            'holding_time': values[13],
            'open_session': values[14],
            'close_session': values[15],
            'trade_type': values[16]
        }
        
        # 显示编辑对话框
        from src.gui.edit_dialog import EditDialog
        dialog = EditDialog(self.root, trade_data)
        result = dialog.show()
        
        if result:
            # 更新交易对显示
            self.trades_tree.item(item, values=(
                result['symbol'],
                result['open_date'],
                result['open_time'],
                result['close_date'],
                result['close_time'],
                f"{result['open_price']:.2f}",
                f"{result['open_qty']:.0f}",
                f"{result['close_price']:.2f}",
                f"{result['close_qty']:.0f}",
                result['direction'],
                f"{result['gross_profit']:.2f}",
                f"{result['net_profit']:.2f}",
                f"{result['commission']:.2f}",
                result['holding_time'],
                result['open_session'],
                result['close_session'],
                result['trade_type']
            ))
            
            # 更新CSV文件
            trades_df = self.trade_processor.file_handler.read_trades()
            # 找到对应的行并更新
            mask = (
                (trades_df['symbol'] == result['symbol']) &
                (trades_df['open_date'] == result['open_date']) &
                (trades_df['open_time'] == result['open_time']) &
                (trades_df['close_date'] == result['close_date']) &
                (trades_df['close_time'] == result['close_time'])
            )
            trades_df.loc[mask] = result
            self.trade_processor.file_handler.update_trades(trades_df)
            
            messagebox.showinfo("Success", "Trade updated successfully!")
    
    def refresh_stats(self):
        """刷新统计信息"""
        trades_df = self.trade_processor.file_handler.read_trades()
        stats = self.trade_processor.calculate_statistics(trades_df)
        
        # 显示统计信息
        self.stats_text.delete(1.0, tk.END)
        for period, data in stats.items():
            self.stats_text.insert(tk.END, f"\n{period.upper()} Statistics:\n")
            self.stats_text.insert(tk.END, str(data) + "\n") 